<?php
/**
 * Created by PhpStorm.
 * User: DD
 * Date: 2016/4/22
 * Time: 17:50
 */

namespace app\admin\services;


use app\common\util\Util;
use think\Db;
use think\View;


class CodeToolService
{
    private static $_titleMap = [
        'creator' => '创建人',
        'create_time' => '创建时间',
        'modify_time' => '修改时间',
        'modifier' => '修改人',
        'name' => '名称',
        'title' => '标题',
        'password' => '密码',
        'url' => '链接地址',
        'thumbnail' => '略缩图',
    ];


    public function getTableList()
    {
        $rows = M()->query('select table_comment title,table_name name from information_schema.tables
where table_schema=\'' . C('database.database') . '\' and table_schema=\'' . C('database.database') . '\'');
        foreach ($rows as &$row) {
            $row['title'] = isset($row['title']) && $row['title'] ? explode(';', $row['title'])[0] : $row['name'];
        }
        return $rows;
    }

    public function getFields($name)
    {
        $name = Util::parseName($name);
        $rows = M()->query('select COLUMN_COMMENT title,COLUMN_NAME name,DATA_TYPE type,COLUMN_DEFAULT defaultvalue,IS_NULLABLE is_null from information_schema.COLUMNS where table_schema=\'' .
            C('database.database')
            . '\' and table_name = \'' . $name . '\'');
        foreach ($rows as &$row) {
            $row['title'] = array_key_exists('title', $row) && $row['title'] ? explode(';', $row['title'])[0]
                : (array_key_exists($row['name'], self::$_titleMap) ? self::$_titleMap[$row['name']] : $row['name']);
            $row['field'] = $row['name'];
        }
        return $rows;
    }

    private function getView()
    {
        $instance = new View();
        if (empty($_GET['old'])) {
            if (!empty($_SERVER['HTTP_REFERER'])) {
                $prefer = $_SERVER['HTTP_REFERER'];
            } else {
                $prefer = $_SERVER['REQUEST_URI'];
            }
            if (strpos($prefer, '/old/') === false) {
                $instance->theme('bootstrap');
            }
        }
        return $instance;
    }

    public function getCode($name, $title)
    {
        define('APP_MODEL_NAME', 'admin');
        return [
            'controller' => $this->getControllerCode($name, $title),
            'service' => $this->getServiceCode($name, $title),
            'html' => $this->getHtmlCode($name, $title),
            'form' => $this->getFormCode($name, $title),
            'detail' => $this->getDetailCode($name, $title)
        ];
    }

    public function getCodeForWeixin($name, $title)
    {
        define('APP_MODEL_NAME', 'weixin');
        return [
            'controller' => $this->getControllerCodeForWeixin($name, $title),
            'modal' => $this->getModalCode($name, $title),
//            'html' => $this->getHtmlCode($name, $title),
            'form' => $this->getFormCodeForWeixin($name, $title),
            'detail' => $this->getDetailCode($name, $title)
        ];
    }

    public function getControllerCode($name, $title)
    {
        $view = $this->getView();
        $view->assign('fields', $this->getFields($name));
        $view->assign('name', $name);
        $view->assign('title', $title);
        $view->assign('module', APP_MODEL_NAME);
        return $view->fetch('codeTool/controller');
    }

    public function getControllerCodeForWeixin($name, $title)
    {
        $view = $this->getView();
        $view->assign('fields', $this->getFields($name));
        $view->assign('name', $name);
        $view->assign('title', $title);
        $view->assign('module', APP_MODEL_NAME);
        return $view->fetch('codeTool/controllerForWeixin');
    }

    public function getServiceCode($name, $title)
    {
        $view = $this->getView();
        $view->assign('fields', $this->getFields($name));
        $view->assign('name', $name);
        $view->assign('title', $title);
        $view->assign('module', APP_MODEL_NAME);
        return $view->fetch('codeTool/service');
    }

    public function getHtmlCode($name, $title)
    {
        $view = $this->getView();
        $view->assign('fields', $this->getFields($name));
        $view->assign('name', $name);
        $view->assign('title', $title);
        $view->assign('module', APP_MODEL_NAME);
        return $view->fetch('codeTool/html');
    }

    public function getDetailCode($name, $title)
    {
        $view = $this->getView();
        $view->assign('displayFields', $this->getFields($name));
        $view->assign('name', $name);
        $view->assign('title', $title);
        $view->assign('module', APP_MODEL_NAME);
        return $view->fetch('codeTool/detail');
    }

    public function getDetailCodeForWeixin($name, $title)
    {
        $view = $this->getView();
        $view->assign('displayFields', $this->getFields($name));
        $view->assign('name', $name);
        $view->assign('title', $title);
        $view->assign('module', APP_MODEL_NAME);
        return $view->fetch('codeTool/detail');
    }

    public function getFormCode($name, $title)
    {
        $view = $this->getView();
        $view->assign('fields', $fields = $this->getFields($name));
        $view->assign('formFields', $fields);
        $view->assign('name', $name);
        $view->assign('title', $title);
        $view->assign('module', APP_MODEL_NAME);
        return $view->fetch('codeTool/form');
    }

    public function getFormCodeForWeixin($name, $title)
    {
        $view = $this->getView();
        $view->assign('fields', $fields = $this->getFields($name));
        $view->assign('formFields', $fields);
        $view->assign('name', $name);
        $view->assign('title', $title);
        $view->assign('module', APP_MODEL_NAME);
        return $view->fetch('codeTool/formForWeixin');
    }

    public function getFormResultCodeForWeixin($name, $title)
    {
        $view = $this->getView();
        $view->assign('fields', $fields = $this->getFields($name));
        $view->assign('formFields', $fields);
        $view->assign('name', $name);
        $view->assign('title', $title);
        $view->assign('module', APP_MODEL_NAME);
        return $view->fetch('codeTool/saveResult');
    }

    public function getModalCode($name, $title)
    {
        $view = $this->getView();
        $view->assign('fields', $fields = $this->getFields($name));
        $view->assign('formFields', $fields);
        $view->assign('name', $name);
        $view->assign('title', $title);
        $view->assign('module', APP_MODEL_NAME);
        return $view->fetch('codeTool/modal');
    }

    private function getTheme()
    {
        static $theme = null;
        if (!is_null($theme)) {
            return $theme;
        }
        $theme = '';
        if (empty($_GET['old'])) {
            if (!empty($_SERVER['HTTP_REFERER'])) {
                $prefer = $_SERVER['HTTP_REFERER'];
            } else {
                $prefer = $_SERVER['REQUEST_URI'];
            }
            if (strpos($prefer, '/old/') === false) {
                $theme = 'bootstrap/';
            }
        }
        return $theme;
    }

    public function createCodeFile($name, $title)
    {
        define('APP_MODEL_NAME', 'admin');
        $data = [
            'controller' => $this->getControllerCode($name, $title),
            'service' => $this->getServiceCode($name, $title),
            'html' => $this->getHtmlCode($name, $title),
            'form' => $this->getFormCode($name, $title),
            'detail' => $this->getDetailCode($name, $title)
        ];
        if (!empty($_GET['controller'])) {
            $this->putfile(APP_PATH . APP_MODEL_NAME . '/controller/' . $name . '.php', $data['controller']);
        }
        if (!empty($_GET['service'])) {
            $this->putfile(APP_PATH . APP_MODEL_NAME . '/services/' . $name . 'Service.php', $data['service']);
        }
        $viewDir = Util::parseName($name);
        if (!empty($_GET['view'])) {
            $this->putfile(APP_PATH . APP_MODEL_NAME . '/view/' . $this->getTheme() . $viewDir . '/index' . '.html', $data['html']);
        }
        if (!empty($_GET['form'])) {
            $this->putfile(APP_PATH . APP_MODEL_NAME . '/view/' . $this->getTheme() . $viewDir . '/form' . '.html', $data['form']);
        }
        if (!empty($_GET['detail'])) {
            $this->putfile(APP_PATH . APP_MODEL_NAME . '/view/' . $this->getTheme() . $viewDir . '/detail' . '.html', $data['detail']);
        }

        return $name . '/index';
    }

    public function createFileForWeixin($name, $title)
    {
        define('APP_MODEL_NAME', 'weixin');
        $data = [
            'controller' => $this->getControllerCodeForWeixin($name, $title),
            'model' => $this->getModalCode($name, $title),
            'form' => $this->getFormCodeForWeixin($name, $title),
            'formResult' => $this->getFormResultCodeForWeixin($name, $title),
            'detail' => $this->getDetailCodeForWeixin($name, $title)
        ];
        if (!empty($_GET['controller'])) {
            $this->putfile(APP_PATH . APP_MODEL_NAME . '/controller/' . $name . '.php', $data['controller']);
        }
        if (!empty($_GET['model'])) {
            $this->putfile(APP_PATH . 'common' . '/model/' . $name . '.php', $data['model']);
        }

        if (!empty($_GET['form'])) {
            $this->putfile(APP_PATH . APP_MODEL_NAME . '/view/default/' . lcfirst($name) . '/index' . '.html', $data['form']);
            $this->putfile(APP_PATH . APP_MODEL_NAME . '/view/default/' . lcfirst($name) . '/saveResult' . '.html', $data['formResult']);
        }
//        if (!empty($_GET['detail'])) {
//            $this->putfile(APP_PATH . APP_MODEL_NAME . '/view/' . $this->getTheme() . lcfirst($name) . '/detail' . '.html', $data['detail']);
//        }

        return $name . '/index';
    }

    private function putfile($path, $content)
    {
        $dir = dirname($path);
        if (!file_exists($dir) || !is_dir($dir)) {
            @mkdir($dir, 0777, true);
            chmod($dir, 0777);
        }
        if (!file_exists($path)) {
            file_put_contents($path, $content);
            @chmod($path, 0777);
        }
    }
}